package libaryinterface.admin;

import libaryinterface.user.UserReturnInterface;
import libaryinterface.interfaceutils.MyDialogDemo;
import pojo.User;
import pojo.vo.BookRecordVo;
import service.BookRecordService;
import service.BookService;
import service.UserService;
import service.impl.BookRecordServiceImpl;
import service.impl.BookServiceImpl;
import service.impl.UserServiceImpl;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 2022-12-07
 * Time: 20:04
 */
public class AdminManageRecordInterface extends JFrame {
    int i =0;
    BookRecordService bookRecordService = new BookRecordServiceImpl();
    BookService bookService = new BookServiceImpl();
    UserService userService = new UserServiceImpl();

    public AdminManageRecordInterface() throws SQLException {
        //设置窗口
        super("借阅信息管理界面");

        Container container = this.getContentPane();
        ImageIcon bg = new ImageIcon("src//picture//admindisplay.jpg");
        JLabel label4 = new JLabel(bg);
        label4.setSize(bg.getIconWidth(),bg.getIconHeight());
        AdminManageRecordInterface.super.getLayeredPane().add(label4,new Integer(Integer.MIN_VALUE));
        //2.把窗口面板设为内容面板并设为透明、流动布局。
        JPanel p1=(JPanel)AdminManageRecordInterface.super.getContentPane();
        p1.setOpaque(false);
        p1.setLayout((new FlowLayout()));
        setBounds(200, 200, 1500, 1200);
        JButton b1 = new JButton("goback");
        JButton b2= new JButton("刷新");
        b2.setBounds(100,900,100,60);
        b1.setBounds(30,55,100,30);
        // 表头（列名）
        Object[][] rowData = new Object[100][11];
        //记录当前的条数
        List<BookRecordVo> bookRecordVoList = bookRecordService.listBookRecord();
        String[] columnNames = {"编号","书名","借阅人", " 借阅时间 ", "规定归还时间","实际归还时间", "是否逾期","借阅天数","借阅数量","罚款金额","是否归还"};
        for (BookRecordVo record: bookRecordVoList) {
            //获取信息
            Long snid =  record.getId();
            String name = record.getName();
            String author = record.getNickName();
            LocalDate lendTime = record.getLendTime();
            LocalDate returnTime = record.getReturnTime();
            LocalDate realTime = record.getRealTime();
            String isOverdue = record.getIsOverdue();
            Long loanLength = record.getLoanLength();
            Long loanNumber = record.getLoanNumber();
            double fineMoney = record.getFineMoney();
            String state = record.getState();
            //放入表格数组中
            rowData[i][0] = snid;
            rowData[i][1] = name;
            rowData[i][2] = author;
            rowData[i][3] = lendTime;
            rowData[i][4] = returnTime;
            rowData[i][5] = realTime;
            rowData[i][6] = isOverdue;
            rowData[i][7] = loanLength;
            rowData[i][8] = loanNumber;
            rowData[i][9] = fineMoney;
            rowData[i][10] = state;
            i++;
        }
        //设置标签
        JLabel label = new JLabel("总数量: " + bookRecordVoList.size());
        label.setBounds(100, 20, 150, 40);
        label.setFont(new Font(null, Font.PLAIN, 20));
        label.setForeground(Color.GREEN);
        JLabel label2 = new JLabel("借阅人账号");
        label2.setForeground(Color.white);
        label2.setFont(new Font(null, Font.PLAIN, 30));
        label2.setBounds(240, 100, 500, 50);
        JTextField l1 = new JTextField(60);
        l1.setBounds(430, 100, 400, 50);
        // 创建一个表格，指定 表头 和 所有行数据
        JTable table = new JTable(rowData, columnNames);

        // 设置表格内容颜色
        table.setForeground(Color.BLACK);                   // 字体颜色
        table.setFont(new Font(null, Font.CENTER_BASELINE, 15));      // 字体样式
        table.setSelectionForeground(Color.DARK_GRAY);      // 选中后字体颜色
        table.setSelectionBackground(Color.YELLOW);     // 选中后字体背景
        table.setGridColor(Color.GRAY);                     // 网格颜色
        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();//单元格渲染器
        tcr.setHorizontalAlignment(JLabel.CENTER);//居中显示
        table.setDefaultRenderer(Object.class, tcr);//设置渲染器
        // 设置表头
        table.getTableHeader().setFont(new Font(null, Font.BOLD, 15));  // 设置表头名称字体样式
        table.getTableHeader().setForeground(Color.RED);                // 设置表头名称字体颜色
        table.getTableHeader().setResizingAllowed(true);               // 设置不允许手动改变列宽
        table.getTableHeader().setReorderingAllowed(false);             // 设置不允许拖动重新排序各列

        // 设置行高
        table.setRowHeight(40);

        // 第一列列宽设置为40
        table.getColumnModel().getColumn(0).setPreferredWidth(40);

        // 设置滚动面板视口大小（超过该大小的行数据，需要拖动滚动条才能看到）
        table.setPreferredScrollableViewportSize(new Dimension(400, 300));
        // 把 表格 放到 滚动面板 中（表头将自动添加到滚动面板顶部）
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBounds(100, 200, 1100, 600);

        //归还按钮
        JButton button1 = new JButton("归还");
        button1.setBounds(650, 890, 100, 50);
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //获取当前的行列数
                int index = 0;
                try {
                    index = table.getSelectedRow();
                    //判断选中行是否有信息
                    if (index >= i) {
                        new MyDialogDemo("请选中有信息的行!");
                        return;
                    }
                    Long recordId = (Long) rowData[index][0]; //获取选中记录的id
                    String bookName = (String) rowData[index][1];//获取选中记录的书名
                    String userName = (String) rowData[index][2]; //获取当前用户的姓名
                    Long reutrnNumber = (Long) rowData[index][8];//获取选中记录的借阅数量
                    String state = (String) rowData[index][10];
                    if(state.equals("是") ){
                        new MyDialogDemo("该书已归还!");
                        return ;
                    }
                    //根据用户姓名获取到用户账号
                    User user = userService.getUserByName(userName);
                    String account = user.getAccount();
                    //进行归还操作
                    boolean flag = bookRecordService.returnRecord(recordId, bookName, reutrnNumber, account);
                    if(flag){
                        //归还成功后自动刷新页面
                        AdminManageRecordInterface.super.dispose();
                        new AdminManageRecordInterface();
                        new MyDialogDemo("归还成功");
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                    new MyDialogDemo("未选中行!");
                }
            }
        });

        //添加按钮
        JButton button2 = new JButton("添加");
        button2.setBounds(500, 890, 100, 50);
        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //获取当前的行列数
                int index = 0;
                try {
                    new AdminAddRecordInterface();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    new MyDialogDemo("未选中行!");
                }
            }
        });
        b1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                AdminManageRecordInterface.super.dispose();
                    new AdminInterface();
            }
        });
        b2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                AdminManageRecordInterface.super.dispose();
                try {
                    new AdminManageRecordInterface();
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        //查询按钮
        JButton button3 = new JButton("查询");
        button3.setBounds(860, 100, 150, 50);
        button3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    //进入归还书籍界面
                    new UserReturnInterface(l1.getText());
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        container.add(b2);
        container.add(b1);
        container.add(l1);
        container.add(label);
        container.add(label2);
        container.add(button1);
        container.add(button2);
        container.add(button3);
        // 添加 滚动面板 到 内容面板
        container.add(scrollPane);
        //获得容器
        container.setBackground(new Color(50, 144, 236));
        container.setLayout(null);
        //container.setVisible(true);
        setBounds(180, 1, 1300, 1200);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
    }
